package com.graduationproject.examonline.examPaper.service;

import com.graduationproject.examonline.examPaper.entity.ExamPaper;
import com.graduationproject.examonline.examPaper.mapper.ExamPaperMapper;
import com.graduationproject.examonline.question.entity.Question;
import com.graduationproject.examonline.question.mapper.QuestionMapper;
import com.graduationproject.examonline.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class ExamPaperService {
    @Autowired
    private ExamPaperMapper examPaperMapper;
    @Autowired
    private QuestionMapper questionMapper;

    public Result insertExamPaper(Map<String, Object> params) {
        try {
            int amount = examPaperMapper.insertExamPaper(params);
            if (amount > 0) {
                return new Result(0, 200, "插入成功");
            } else {
                return new Result(1, 200, "插入失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1, 500, "插入失败");
        }
    }

    public Result getQuestionListByExamPaperId(String exam_paper_id) {
        try {
            List<ExamPaper> examPaperList = examPaperMapper.getExamPaperById(exam_paper_id);
            if (examPaperList.size() > 0) {
                ExamPaper examPaper = examPaperList.get(0);
                String[] question_id_list = examPaper.getQuestion_id_list().split(",");
                String[] question_score_list = examPaper.getQuestion_score_list().split(",");
                List<Map<String, Object>> questionList = new LinkedList<Map<String, Object>>();
                for (int index = 0; index < question_id_list.length; index += 1) {
                    Question question = questionMapper.getQuestionById(question_id_list[index]).get(0);
                    Map<String, Object> question2 = new HashMap<String, Object>();
                    question2.put("question_id", question.getQuestion_id());
                    question2.put("question_type", question.getQuestion_type());
                    question2.put("question_context", question.getQuestion_context());
                    question2.put("options", question.getOptions());
                    question2.put("true_answer", question.getTrue_answer());
                    question2.put("score", question_score_list[index]);
                    questionList.add(question2);
                }
                return new Result(0, 200, "ok", questionList);
            } else {
                return new Result(1, 200, "无记录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1, 500, "error");
        }
    }
}
